/**
 * 编辑器状态管理
 * 使用Pinia管理编辑器的全局状态
 */
import { defineStore } from 'pinia'
import { ref, computed, reactive, watch } from 'vue'
import type {
  ProjectData,
  AssetData,
  AssetType
} from '../services/types'

// 编辑器专用类型
export interface EditorLayer {
  id: string
  name: string
  visible: boolean
  locked: boolean
  type: AssetType
  position: { x: number; y: number }
  scale: { x: number; y: number }
  rotation: number
  opacity: number
  assetId?: string
  zIndex: number
}

export interface EditorKeyframe {
  id: string
  time: number
  value: Record<string, any>
  easing?: 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out'
}

export interface EditorTrack {
  id: string
  name: string
  type: string
  layerId: string
  visible: boolean
  locked: boolean
  keyframes: EditorKeyframe[]
  clips?: Array<{
    id: string
    name: string
    startTime: number
    endTime: number
    assetId?: string
  }>
}

export interface EditorAssets {
  characters: AssetData[]
  scenes: AssetData[]
  props: AssetData[]
  effects: AssetData[]
  audio: AssetData[]
}

export interface PlaybackState {
  isPlaying: boolean
  currentTime: number
  totalDuration: number
  playbackSpeed: number
  loop: boolean
}

export interface ViewportState {
  zoom: number
  panX: number
  panY: number
  width: number
  height: number
}

export interface SelectionState {
  selectedLayers: string[]
  selectedTracks: string[]
  selectedKeyframes: string[]
  multiSelect: boolean
}

export interface HistoryState {
  canUndo: boolean
  canRedo: boolean
  maxHistorySize: number
}

export const useEditorStore = defineStore('editor', () => {
  // 项目数据
  const currentProject = ref<ProjectData | null>(null)
  const projectModified = ref(false)
  
  // 图层管理
  const layers = ref<EditorLayer[]>([])
  const layerOrder = ref<string[]>([])
  
  // 轨道管理
  const tracks = ref<EditorTrack[]>([])
  
  // 素材库
  const assets = reactive<EditorAssets>({
    characters: [],
    scenes: [],
    props: [],
    effects: [],
    audio: []
  })
  
  // 播放状态
  const playback = reactive<PlaybackState>({
    isPlaying: false,
    currentTime: 0,
    totalDuration: 0, // 将根据轨道内容动态计算
    playbackSpeed: 1.0,
    loop: false
  })
  
  // 视口状态
  const viewport = reactive<ViewportState>({
    zoom: 1.0,
    panX: 0,
    panY: 0,
    width: 800,
    height: 600
  })
  
  // 选择状态
  const selection = reactive<SelectionState>({
    selectedLayers: [],
    selectedTracks: [],
    selectedKeyframes: [],
    multiSelect: false
  })
  
  // 历史状态
  const history = reactive<HistoryState>({
    canUndo: false,
    canRedo: false,
    maxHistorySize: 50
  })
  
  // 时间轴状态
  const timelineZoom = ref(20) // 每秒像素数，200px = 10秒，所以20px/秒
  const timelineHeight = ref(200)
  const timelineSidebarWidth = ref(160)
  
  // UI状态
  const leftSidebarWidth = ref(280)
  const rightSidebarWidth = ref(280)
  const showGrid = ref(true)
  const snapToGrid = ref(true)
  const gridSize = ref(20)
  const isRealTimeRender = ref(true)
  
  // 计算属性
  const selectedLayer = computed(() => {
    if (selection.selectedLayers.length === 1) {
      return layers.value.find(layer => layer.id === selection.selectedLayers[0])
    }
    return null
  })
  
  const selectedTrack = computed(() => {
    if (selection.selectedTracks.length === 1) {
      return tracks.value.find(track => track.id === selection.selectedTracks[0])
    }
    return null
  })
  
  const selectedKeyframe = computed(() => {
    if (selection.selectedKeyframes.length === 1) {
      for (const track of tracks.value) {
        const keyframe = track.keyframes.find(kf => kf.id === selection.selectedKeyframes[0])
        if (keyframe) return keyframe
      }
    }
    return null
  })
  
  const visibleLayers = computed(() => {
    return layers.value
      .filter(layer => layer.visible)
      .sort((a, b) => a.zIndex - b.zIndex)
  })
  
  // 计算总时长 - 基于所有轨道中最长的内容
  const calculatedTotalDuration = computed(() => {
    let maxDuration = 0

    // 遍历所有轨道
    for (const track of tracks.value) {
      // 检查关键帧
      if (track.keyframes && track.keyframes.length > 0) {
        const lastKeyframe = Math.max(...track.keyframes.map(kf => kf.time))
        maxDuration = Math.max(maxDuration, lastKeyframe)
      }

      // 检查片段
      if (track.clips && track.clips.length > 0) {
        const lastClipEnd = Math.max(...track.clips.map(clip => clip.endTime))
        maxDuration = Math.max(maxDuration, lastClipEnd)
      }
    }

    // 如果没有内容，返回默认的30秒
    return maxDuration > 0 ? maxDuration + 5 : 30 // 额外5秒缓冲
  })

  const timelineTicks = computed(() => {
    const ticks: number[] = []
    const duration = calculatedTotalDuration.value
    const tickInterval = timelineZoom.value >= 20 ? 0.1 : timelineZoom.value >= 10 ? 0.5 : 1
    for (let i = 0; i <= duration; i += tickInterval) {
      ticks.push(i)
    }
    return ticks
  })
  
  // Actions - 项目管理
  const loadProject = (project: ProjectData) => {
    currentProject.value = project
    projectModified.value = false
    // TODO: 从项目数据加载图层和轨道
  }
  
  const saveProject = async () => {
    if (!currentProject.value) return
    // TODO: 保存项目逻辑
    projectModified.value = false
  }
  
  const markProjectModified = () => {
    projectModified.value = true
  }
  
  // Actions - 图层管理
  const addLayer = (layer: Omit<EditorLayer, 'id' | 'zIndex'>) => {
    const newLayer: EditorLayer = {
      ...layer,
      id: `layer-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      zIndex: layers.value.length
    }
    layers.value.push(newLayer)
    layerOrder.value.push(newLayer.id)
    markProjectModified()
    return newLayer
  }
  
  const removeLayer = (layerId: string) => {
    const index = layers.value.findIndex(layer => layer.id === layerId)
    if (index !== -1) {
      layers.value.splice(index, 1)
      layerOrder.value = layerOrder.value.filter(id => id !== layerId)
      
      // 移除相关轨道
      tracks.value = tracks.value.filter(track => track.layerId !== layerId)
      
      // 清除选择
      selection.selectedLayers = selection.selectedLayers.filter(id => id !== layerId)
      markProjectModified()
    }
  }
  
  const updateLayer = (layerId: string, updates: Partial<EditorLayer>) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      Object.assign(layer, updates)
      markProjectModified()
    }
  }
  
  // Actions - 轨道管理
  const addTrack = (track: Omit<EditorTrack, 'id'>) => {
    const newTrack: EditorTrack = {
      ...track,
      id: `track-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    }
    tracks.value.push(newTrack)
    markProjectModified()
    return newTrack
  }
  
  const removeTrack = (trackId: string) => {
    const index = tracks.value.findIndex(track => track.id === trackId)
    if (index !== -1) {
      tracks.value.splice(index, 1)
      selection.selectedTracks = selection.selectedTracks.filter(id => id !== trackId)
      markProjectModified()
    }
  }
  
  const updateTrack = (trackId: string, updates: Partial<EditorTrack>) => {
    const track = tracks.value.find(t => t.id === trackId)
    if (track) {
      Object.assign(track, updates)
      markProjectModified()
    }
  }
  
  // Actions - 关键帧管理
  const addKeyframe = (trackId: string, keyframe: Omit<EditorKeyframe, 'id'>) => {
    const track = tracks.value.find(t => t.id === trackId)
    if (track) {
      const newKeyframe: EditorKeyframe = {
        ...keyframe,
        id: `keyframe-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      }
      track.keyframes.push(newKeyframe)
      track.keyframes.sort((a, b) => a.time - b.time)
      markProjectModified()
      return newKeyframe
    }
    return null
  }
  
  const removeKeyframe = (trackId: string, keyframeId: string) => {
    const track = tracks.value.find(t => t.id === trackId)
    if (track) {
      track.keyframes = track.keyframes.filter(kf => kf.id !== keyframeId)
      selection.selectedKeyframes = selection.selectedKeyframes.filter(id => id !== keyframeId)
      markProjectModified()
    }
  }
  
  const updateKeyframe = (trackId: string, keyframeId: string, updates: Partial<EditorKeyframe>) => {
    const track = tracks.value.find(t => t.id === trackId)
    if (track) {
      const keyframe = track.keyframes.find(kf => kf.id === keyframeId)
      if (keyframe) {
        Object.assign(keyframe, updates)
        track.keyframes.sort((a, b) => a.time - b.time)
        markProjectModified()
      }
    }
  }
  
  // Actions - 选择管理
  const selectLayer = (layerId: string, multiSelect = false) => {
    if (multiSelect) {
      if (selection.selectedLayers.includes(layerId)) {
        selection.selectedLayers = selection.selectedLayers.filter(id => id !== layerId)
      } else {
        selection.selectedLayers.push(layerId)
      }
    } else {
      selection.selectedLayers = [layerId]
    }
    selection.multiSelect = multiSelect
  }
  
  const selectTrack = (trackId: string, multiSelect = false) => {
    if (multiSelect) {
      // 多选模式：切换选择状态
      if (selection.selectedTracks.includes(trackId)) {
        // 如果已选中，则取消选择
        selection.selectedTracks = selection.selectedTracks.filter(id => id !== trackId)
      } else {
        // 如果未选中，则添加到选择列表
        selection.selectedTracks.push(trackId)
      }
    } else {
      // 单选模式：切换选择状态
      if (selection.selectedTracks.length === 1 && selection.selectedTracks[0] === trackId) {
        // 如果当前只选中了这一个轨道，则取消选择
        selection.selectedTracks = []
      } else {
        // 否则选中这个轨道
        selection.selectedTracks = [trackId]
      }
    }
    selection.multiSelect = multiSelect
  }
  
  const selectKeyframe = (keyframeId: string, multiSelect = false) => {
    if (multiSelect) {
      if (selection.selectedKeyframes.includes(keyframeId)) {
        selection.selectedKeyframes = selection.selectedKeyframes.filter(id => id !== keyframeId)
      } else {
        selection.selectedKeyframes.push(keyframeId)
      }
    } else {
      selection.selectedKeyframes = [keyframeId]
    }
    selection.multiSelect = multiSelect
  }
  
  const clearSelection = () => {
    selection.selectedLayers = []
    selection.selectedTracks = []
    selection.selectedKeyframes = []
    selection.multiSelect = false
  }
  
  // Actions - 播放控制
  const play = () => {
    playback.isPlaying = true
  }
  
  const pause = () => {
    playback.isPlaying = false
  }
  
  const stop = () => {
    playback.isPlaying = false
    playback.currentTime = 0
  }
  
  const seekTo = (time: number) => {
    playback.currentTime = Math.max(0, Math.min(calculatedTotalDuration.value, time))
  }

  // 监听轨道变化，自动更新总时长
  watch(calculatedTotalDuration, (newDuration) => {
    playback.totalDuration = newDuration
  }, { immediate: true })

  return {
    // State
    currentProject,
    projectModified,
    layers,
    layerOrder,
    tracks,
    assets,
    playback,
    viewport,
    selection,
    history,
    timelineZoom,
    timelineHeight,
    timelineSidebarWidth,
    leftSidebarWidth,
    rightSidebarWidth,
    showGrid,
    snapToGrid,
    gridSize,
    isRealTimeRender,
    
    // Computed
    selectedLayer,
    selectedTrack,
    selectedKeyframe,
    visibleLayers,
    timelineTicks,
    calculatedTotalDuration,
    
    // Actions
    loadProject,
    saveProject,
    markProjectModified,
    addLayer,
    removeLayer,
    updateLayer,
    addTrack,
    removeTrack,
    updateTrack,
    addKeyframe,
    removeKeyframe,
    updateKeyframe,
    selectLayer,
    selectTrack,
    selectKeyframe,
    clearSelection,
    play,
    pause,
    stop,
    seekTo
  }
})
